﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Surface;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;
using Microsoft.Surface.Presentation.Input;



namespace CitiSurface
{
    /// <summary>
    /// Interaction logic for IdTagVisualization.xaml
    /// </summary>
    public partial class IdTagVisualization : TagVisualization
    {
        /// <summary>
        /// This event fires when we drop the tag.
        /// </summary>
        public static readonly RoutedEvent ShowMenuEvent = EventManager.RegisterRoutedEvent(
            "ShowMenu",
            RoutingStrategy.Bubble,
            typeof(RoutedEventHandler),
            typeof(IdTagVisualization));
        
        /// <summary>
        /// This event fires when click the profile button to open.
        /// </summary>
        public static readonly RoutedEvent ShowProfileEvent = EventManager.RegisterRoutedEvent(
            "ShowProfile",
            RoutingStrategy.Bubble,
            typeof (RoutedEventHandler),
            typeof (IdTagVisualization));

        /// <summary>
        ///  This event fires when click the profile button to close
        /// </summary>
        public static readonly RoutedEvent CloseProfileEvent = EventManager.RegisterRoutedEvent(
            "CloseProfile",
            RoutingStrategy.Bubble,
            typeof(RoutedEventHandler),
            typeof(IdTagVisualization));

        public event RoutedEventHandler ShowMenu
        {
            add { AddHandler(ShowMenuEvent, value); }
            remove { RemoveHandler(ShowMenuEvent, value); }
        }

        public event RoutedEventHandler ShowProfile
        {
            add{AddHandler(ShowProfileEvent,value);}
            remove {RemoveHandler(ShowProfileEvent,value);}
        }
        
        public event RoutedEventHandler CloseProfile
        {
            add {AddHandler(CloseProfileEvent,value);}
            remove {RemoveHandler(CloseProfileEvent,value);}
        }

        public IdTagVisualization()
        {
            InitializeComponent();
            
        }
        /// <summary>
        /// This method loaded when visualization start
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IdTagVisualization_Loaded(object sender, RoutedEventArgs e)
        {
            //TODO: customize IdTagVisualization's UI based on this.VisualizedTag here
            IdTagViewModel dataModel = this.DataContext as IdTagViewModel;
            AddProfiles(dataModel.Interviewers);
            AddScheduleAndJob(dataModel.Interviews);
            PopulateItemCircle();
            

            // announce that we've disassociated the image with the tag
            // the XAML style will take care of showing/hiding UI elements as necessary
            RoutedEventArgs e2 = new RoutedEventArgs(ShowMenuEvent, this);
            RaiseEvent(e2);
        }
        /// <summary>
        /// Generate the profile scattervierwitems, add the profile information into the myTagFile scatterview
        /// </summary>
        /// <param name="interviewers"></param>
        private void AddProfiles(ObservableCollection<Interviewer> interviewers)
        {
            int index = 0;
            foreach (var interviewer in interviewers)
            {
                SurfaceButton sb = new SurfaceButton();
                var svi = new ScatterViewItem
                              {
                                  Name = interviewer.FirstName,
                                  Orientation = 0,
                                  Visibility = Visibility.Collapsed,
                                  CanScale = false
                              };
                svi.IsVisibleChanged +=new DependencyPropertyChangedEventHandler(myProfileView_IsVisibleChanged);
                
                sb.DataContext = (Interviewer)interviewer;
                sb.Margin = new Thickness(2,2,2,2);
                sb.Style = (Style)FindResource("Profile_Style");
                sb.Click += new RoutedEventHandler(sb_Click2);

                svi.Content = sb;
                myTagFiles.Items.Add(svi);
                PopulateProfileCircle(interviewers);
                index++;
            }
        }

        void sb_Click2(object sender, RoutedEventArgs e)
        {
            var sb = sender as SurfaceButton;
            var svi = sb.Parent as ScatterViewItem;
            if(svi.Visibility == Visibility.Visible)
            {
                svi.Visibility = Visibility.Collapsed;
            }
        }
        /// <summary>
        /// Generate the schedule and job scatterviewitems, add the schedule and job information into the myTagFile scatterview
        /// </summary>
        /// <param name="interviews"></param>
        private void AddScheduleAndJob(ObservableCollection<Interview> interviews)
        {
            var svi = new ScatterViewItem { Name = "itinerary", Orientation = 0, Visibility = Visibility.Collapsed, CanScale = false};
            svi.IsVisibleChanged +=new DependencyPropertyChangedEventHandler(myProfileView_IsVisibleChanged);
            
            var grid = new Grid {Opacity = 1};
            grid.Height = double.NaN;
            for (int i = 0; i < 2; i++)
            {
                RowDefinition cd = new RowDefinition();
                grid.RowDefinitions.Add(cd);
            }
            grid.RowDefinitions[0].Height=new GridLength(100);
            
            var rectangle1 = new Rectangle
                                 {      
                                     Name = "Background",
                                     RenderTransformOrigin = new Point(0.5, 0.5),
                                     StrokeThickness = 1.0,
                                 };
            rectangle1.Height = double.NaN;
            rectangle1.Width = double.NaN;
            RadialGradientBrush rgb1= (RadialGradientBrush)FindResource("BackgroundBrush");
            rectangle1.Fill = rgb1;
            RadialGradientBrush rgb2 = (RadialGradientBrush)FindResource("BackgroundStrokeBrush");
            rectangle1.Stroke = rgb2;
            var rectangle2 = new Rectangle
                                {
                                    Name = "Highlight",
                                    RenderTransformOrigin = new Point(0.5, 0.5),
                                    Margin = new Thickness(1,1,1,1),
                                    Opacity = 0.8
                                };
            rectangle2.Height = double.NaN;
            rectangle2.Width = double.NaN;
            RadialGradientBrush rgb3 = (RadialGradientBrush)FindResource("HighlightBrush");
            rectangle2.Fill = rgb3;
            
            var stack1 = new StackPanel {Background = new SolidColorBrush(Color.FromRgb(30,196,244)), Orientation = System.Windows.Controls.Orientation.Horizontal };
            stack1.SetValue(Grid.RowProperty,0);
            Image img = new Image();
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri("Items/itinerary.png", UriKind.Relative);
            bi.EndInit();
            img.Source = bi;
            img.Width = 100;
            var label1 = new Label { VerticalAlignment = VerticalAlignment.Center,Content = "Interview Schedule", FontSize = 20 };
            stack1.Children.Add(img);
            stack1.Children.Add(label1);
            
            var stack3 = new StackPanel { Orientation = System.Windows.Controls.Orientation.Vertical };
            stack3.Height = double.NaN;
            stack3.SetValue(Grid.RowProperty,1);
            foreach (var interview in interviews)
            {
                var stack2 = new StackPanel { Background = new SolidColorBrush(Color.FromRgb(255, 255, 255)), Orientation = System.Windows.Controls.Orientation.Horizontal };
                var label2 = new Label { Foreground = new SolidColorBrush(Color.FromRgb(0, 0, 0)), Content = interview.StartTime + " v.s.", FontSize = 15 };
                var label3 = new Label { Foreground = new SolidColorBrush(Color.FromRgb(0, 0, 0)),Content = interview.Interviewer.FirstName +
                                        " "+interview.Interviewer.LastName, FontSize = 15};
                
                stack2.Children.Add(label2);
                stack2.Children.Add(label3);
                stack3.Children.Add(stack2);
            }
            grid.Children.Add(rectangle1);
            grid.Children.Add(stack1);
            grid.Children.Add(stack3);
            grid.Children.Add(rectangle2);
           
            SurfaceButton sb = new SurfaceButton();
            sb.Click +=new RoutedEventHandler(sb2_Click);
            sb.Content = grid;
            svi.Content = sb;
            svi.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
            myTagFiles.Items.Add(svi);

            SurfaceButton sb2 = new SurfaceButton();
            var svi2 = new ScatterViewItem
            {
                Name = "job",
                Orientation = 0,
                Visibility = Visibility.Collapsed,
                CanScale = false
            };
            svi2.IsVisibleChanged += new DependencyPropertyChangedEventHandler(myProfileView_IsVisibleChanged);
            sb2.DataContext = (Interview)interviews[0];
            sb2.Margin = new Thickness(2, 2, 2, 2);
            sb2.Style = (Style)FindResource("Job_Style");
            sb2.Click +=new RoutedEventHandler(sb2_Click);
            svi2.Content = sb2;
            myTagFiles.Items.Add(svi2);
        }


        private void sb2_Click(object sender, RoutedEventArgs e)
        {
            var sb = sender as SurfaceButton;
            var svi = sb.Parent as ScatterViewItem;
            if (svi.Visibility == Visibility.Visible)
            {
                svi.Visibility = Visibility.Collapsed;
            }
        }

       

        /// <summary>
        /// Populates the circle of items with buttons showing menu
        /// </summary>
        private void PopulateItemCircle()
        {
            // only add the menu button to the circle once.
            // if there are menu button in the canvas 
            //  then we have already added them and do not need to add them again
            if (ItemCanvas.Children.Count == 0)
            {
                string itemsFolder = Directory.GetCurrentDirectory();
                itemsFolder += @"\Items\";
                string[] photosFiles =
                    Directory.GetFiles(itemsFolder, "*.png");

                double segment = 270.0 / photosFiles.Length;
                double rotation = -90.0;

                foreach (string pic in photosFiles)
                {
                    
                    AddImageToCircle(System.IO.Path.GetFileNameWithoutExtension(pic),pic, rotation, ItemCanvas);
                    rotation += segment;
                }
            }
        }
        /// <summary>
        /// Add the profile picuture buttons into the ProfileCanvas
        /// </summary>
        /// <param name="interviewers"></param>
        private void PopulateProfileCircle(ObservableCollection<Interviewer> interviewers)
        {
            if (ProfileCanvas.Children.Count == 0)
            {
                double segment = 180.0/interviewers.Count;
                double rotation = 120.0;
                foreach (var interviewer in interviewers)
                {
                    AddImageToCircle(interviewer.FirstName, interviewer.ProfilePic, rotation, ProfileCanvas);
                    rotation += segment;
                }
            }
        }

       

        /// <summary>
        /// Helper method to load an image from a path
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static Image LoadImageFromPath(string path)
        {
            ImageSourceConverter converter = new ImageSourceConverter();
            Image image = new Image();
            image.Source = (ImageSource)converter.ConvertFromString(path);
            return image;
        }

        /// <summary>
        /// Add an image to the image circle
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pic"></param>
        /// <param name="stack"></param>
        /// <param name="rotation"></param>
        private void AddImageToCircle(string name, string pic, double rotation, Canvas targetCanvas)
        {
            SurfaceButton sb = new SurfaceButton();
            sb.Name = name;

            // load the file into an Image object to use as the content 
            Image img = LoadImageFromPath(pic);
            
            if (targetCanvas == ItemCanvas)
            {
                 // apply the xaml style to the surface content control
                sb.Style = (Style)FindResource("SB_Style");
                img.Width = 85;
                img.Height = 85;
            }
            if (targetCanvas == ProfileCanvas)
            {
                sb.Style = (Style) FindResource("PB_Style");
                img.Width = 45;
                img.Height = 60;
            }
            
            //add the control to the circle
            sb.Margin = new Thickness(100, 0, 0, 0);

            //Rotate the Surface Button so that the highlight on the Glass Button is coming from that same place on all of them.
            double circleRadius = targetCanvas.Height / 2;
            double radians = rotation * Math.PI / 180.0;
            double x = circleRadius * Math.Cos(radians);
            double y = circleRadius * Math.Sin(radians) + targetCanvas.Height / 2;
            TranslateTransform tt = new TranslateTransform(x, y);
            sb.RenderTransformOrigin = new Point(0.5, 0.5);
            sb.RenderTransform = tt;

            sb.Content = img;

            

            // add an event handler for a click on this image
            sb.Click += new RoutedEventHandler(sb_Click);
            
            //place the scc at the correct location on the circle
            targetCanvas.Children.Add(sb);
        }

       
        /// <summary>
        /// When the menus are clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sb_Click(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            SurfaceButton sb = sender as SurfaceButton;
           
            if (sb.Name.Equals("interviewer"))
            {
                if (ProfileCanvas.Visibility == Visibility.Collapsed)
                {
                    Storyboard myShowProfileStoryboard = (Storyboard)FindResource("ShowProfile"); ;
                    myShowProfileStoryboard.Begin(sb);  
                }
                else
                {
                    Storyboard myShowProfileStoryboard = (Storyboard)FindResource("CloseProfile"); ;
                    myShowProfileStoryboard.Begin(sb);  
                }
                
                //showProfilePic(sb);
                //RoutedEventArgs e1 = new RoutedEventArgs(SurfaceButton.ClickEvent);
                //RaiseEvent(e1);
                //foreach (ScatterViewItem svi in myTagFiles.Items)
                //{
                //    if (svi.Name.Contains("interviewer"))
                //    {
                //        svi.Visibility = svi.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
                //    }
                //}
            }
            else if (sb.Name.Equals("itinerary"))
            {
                foreach (ScatterViewItem svi in myTagFiles.Items)
                {
                    if (svi.Name.Contains("itinerary"))
                    {
                        svi.Visibility = svi.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
                    }
                }
            }
            else if (sb.Name.Equals("job"))
            {
                foreach (ScatterViewItem svi in myTagFiles.Items)
                {
                    if (svi.Name.Contains("job"))
                    {
                        svi.Visibility = svi.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
                    }
                }
            }
            else
            {
                foreach (ScatterViewItem svi in myTagFiles.Items)
                {
                    if (svi.Name.Equals(sb.Name))
                    {
                        svi.Visibility = svi.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
                    }
                }
            }
        }

        private void myProfileView_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var sci = sender as ScatterViewItem;
            if (sci != null)
            {
                var sbPoint = sci.ActualCenter;
                sci.Center = sbPoint+new Vector(-2,2);
            }
        }
    }
}
